<?php

namespace backend\controllers;

use common\business\CommonHelper;
use common\business\file\FileHelper;
use common\business\task\TaskResponseData;
use common\consts\CommonResources;
use common\consts\Consts;
use common\helpers\DateHelper;
use common\models\Task;
use common\result\ActionResult;
use Yii;
use common\models\File;
use common\models\FileSearch;
use yii\db\Exception;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * FileController implements the CRUD actions for File model.
 */
class FileController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all File models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new FileSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single File model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new File model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new File();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->file_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing File model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->file_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing File model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the File model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return File the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = File::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionDeleteByFilename($filename){

        $fileName4check = iconv('utf-8', 'GBK//TRANSLIT//IGNORE', $filename);

        $fileInDb = File::findOne([
            'file_name' => $filename
        ]);

        if (!$fileInDb){
            return Json::encode(new TaskResponseData(TaskResponseData::CODE_SUCCESS, 'File is not existed any more'));
        }

        $filePath = $fileInDb->file_path.$fileName4check;

        if (!unlink($filePath)){
            return Json::encode(new TaskResponseData(TaskResponseData::CODE_ERROR, 'File delete fail'));
        }
        if (!$fileInDb->delete()){
            return Json::encode(new TaskResponseData(TaskResponseData::CODE_ERROR, 'File Record delete fail'));
        }

        return Json::encode(new TaskResponseData(TaskResponseData::CODE_SUCCESS, CommonResources::ACTION_NAME_MODEL_SUCCESS('File', 'Delete', $filename)));
    }

    public function actionUpload(){
        $file = UploadedFile::getInstanceByName('file');
        $path = Yii::getAlias('@backend/runtime/uploads/');
        $allow_extensions = ['xls', 'xlsx', 'csv'];
        $task_type = Consts::TASK_TYPE_EXCEL_TO_EMPLOYEE;

        $response = FileHelper::upload($file, $path, $allow_extensions, $task_type);
        return Json::encode($response);
    }

    public function actionGenerateTask($id){
        $fileInDb = File::findOne($id);
        if (!$fileInDb){
            $result =  new ActionResult(false, CommonResources::ACTION_FAIL_MSG('Generate', 'Task', 'File not found'));
            Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
            return $this->redirect(['index']);
        }

        $task = new Task([
            'type' => Consts::TASK_TYPE_EXCEL_TO_EMPLOYEE,
            'priority' => 1,
            'key' => strval($fileInDb->file_id),
            'from_system' => 'hr',
            'request_data' => '',
            'status' => Consts::TASK_STATUS_OPEN,
            'is_synchronization' => Consts::NO,
            'next_run_date' => DateHelper::getCurrentDateTime(-30),
        ]);

        try{
            $isSuccess = CommonHelper::persistRecord($task);
            $result = new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG('Create Excel Task', 'Employee'));
            Yii::$app->getSession()->setFlash('success', Yii::t('app', $result->message));
            return $this->redirect(['/task/index']);
        }
        catch (Exception $e){
            $result =  new ActionResult(false, CommonHelper::getExceptionMsg($e), false, $e);
            Yii::$app->getSession()->setFlash('error', Yii::t('app', $result->message));
            return $this->redirect(['index']);
        }
    }
}
